const DataLoader = require('dataloader')
import { User, UserGroup, Group } from '../../models'
import { placeData } from '../../lib/graphql'

export const usersLoader = () =>
  new DataLoader(
    async keys => {
      let ugs = await UserGroup.findAll({ where: { groupId: { $in: keys } } })
      let uids = ugs.map(n => {
        return n.userId
      })
      let data = await User.findAll({ where: { id: { $in: uids } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const groupLoader = () =>
  new DataLoader(
    async keys => {
      let data = await Group.findAll({ where: { id: { $in: keys } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )
